import { huanJing } from './huanJing/HuanJing.js'
import { wuLiWorker } from './wuLi/WuLiWorker.js'
import { jieMian } from './jieMian/zhuCeZuJian.js'
import { CunChu } from './cunChu/CunChu.js'
import { ChangJing } from './changJing/ChangJing.js'
import { gengXin, tongBu } from './gengXin/gengXin.js'
import { zhuCeShiJian } from './kongZhi/zhuCeShiJian.js'

export async function qiDong() {
	// 加载中页面
	let jiaZaiZhong = jieMian.jiaZaiZhong
	// 加载资源
	let jinDu = [wuLiWorker.jiaZaiAmmo()]
	jinDu.forEach(p => p.then(() => jiaZaiZhong.setAttribute('jin-du-jia', 100 / jinDu.length)))
	await Promise.all(jinDu)
	// 存储
	let cunChu = new CunChu()
	await cunChu.jiaZai()
	// 开始菜单
	let kaiShiCaiDan = jieMian.kaiShiCaiDan
	kaiShiCaiDan.show()
	await kaiShiCaiDan.kaiShi()
	jiaZaiZhong.yinCang()
	// 加载场景
	let changJing = new ChangJing()
	changJing.jiaZai()
	// 注册控制事件
	zhuCeShiJian()
	// 渲染ID
	let requestID = null
	
	function animate() {
		render()
		// setTimeout(animate, 1/60) // 最小4ms； 误打误撞stepSimulation发现步长过大 2023/9/13-14
		requestID = requestAnimationFrame(animate) // 放最后,报错停止渲染
	}
	
	function render() {

		let jianGeShi = huanJing.clock.getDelta() // 间隔时
		// 按顺序
		gengXin(jianGeShi) // 物理操作前的各种更新
		wuLiWorker.gengXinCaoZuo(jianGeShi) // 先实施物理操作。可能会被步进模拟后的状态覆盖
		// 再获取物体状态
		wuLiWorker.huoQuWuTi(jianGeShi).then(wuLiShuZu => tongBu(wuLiShuZu))
		
		huanJing.xuanRan()
	}
	
	animate()
	
	// window.addEventListener("beforeunload", (event) => {
	// 	event.preventDefault();
	// 	event.returnValue = "";
	// 	cancelAnimationFrame(requestID)
	// })
}